package com.caroil.caroilservice.activitys.login.vmode;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.caroil.caroilservice.R;
import com.caroil.caroilservice.base.BaseApplation;
import com.caroil.caroilservice.base.BaseViewMode;
import com.caroil.caroilservice.base.ConfigureFile;
import com.caroil.caroilservice.bean.BaseBean;
import com.caroil.caroilservice.bean.LoginBean;
import com.caroil.caroilservice.network.RequestUtils;
import com.caroil.caroilservice.network.Utils.MyObserver;
import com.caroil.caroilservice.util.SPUtil;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.king.base.util.ToastUtils;

import java.util.List;

import androidx.lifecycle.MutableLiveData;
import cn.jiguang.verifysdk.api.JVerificationInterface;
import cn.jiguang.verifysdk.api.JVerifyUIConfig;
import cn.jiguang.verifysdk.api.VerifyListener;

public class LoginMode extends BaseViewMode {
    private MutableLiveData<String> selfPhone;//获取本机手机号码
    private Activity activity;
    private int winWidth;
    private int winHeight;

    public MutableLiveData<String> getLivePhone() {
        if (selfPhone == null)
            selfPhone = new MutableLiveData<>();
        return selfPhone;
    }

    /**
     * 获取本机手机号码权限
     *
     * @param activity
     */
    private void getPhonePermissions(Activity activity) {
        XXPermissions.with(activity)
                // 可设置被拒绝后继续申请，直到用户授权或者永久拒绝
                .constantRequest()
                // 支持请求6.0悬浮窗权限8.0请求安装权限
                //.permission(Permission.SYSTEM_ALERT_WINDOW, Permission.REQUEST_INSTALL_PACKAGES)
                // 不指定权限则自动获取清单中的危险权限
                .permission(Permission.READ_PHONE_STATE)
                .request(new OnPermission() {

                    @Override
                    public void hasPermission(List<String> granted, boolean all) {
                        getPhone();
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {

                    }
                });
    }

    /**
     * 判断用户是否给了获取本机手机号的权限
     */
    public void judgeIfHavePhonePermission(Activity activity, int winWidth, int winHeight) {
        this.activity = activity;
        this.winHeight = winHeight;
        this.winWidth = winWidth;
        if (XXPermissions.isHasPermission(activity.getApplicationContext(), Permission.READ_PHONE_STATE)) {
            getPhone();
        } else {
            selfPhone.postValue("1002");
            getPhonePermissions(activity);
        }
    }

    private void getPhone() {
        JVerificationInterface.setCustomUIWithConfig(getDialogPortraitConfig(activity, winWidth, winHeight));
        JVerificationInterface.loginAuth(activity, (code, token, s1) -> {
            if (code == 6000) {
                RequestUtils.Login(activity, token, new MyObserver<LoginBean>(activity, false) {
                    @Override
                    public void onSuccess(LoginBean loginBean) {
                        setConfigure(loginBean);
                    }

                    @Override
                    public void onFailure(Throwable e, String errorMsg, int code) {
                        selfPhone.postValue("201");
                        Toast.makeText(BaseApplation.instance(), errorMsg, Toast.LENGTH_SHORT).show();
                    }
                });


            } else {
                selfPhone.postValue("1001");
                toFailedActivigy(code, token);
            }
        });
    }

    /**
     * 获取手机短信验证码
     *
     * @param context
     * @param phone
     */
    public void getPhoneCode(Context context, String phone) {
        RequestUtils.getPhoneCode(context, phone, new MyObserver<BaseBean>(context, true) {
            @Override
            public void onSuccess(BaseBean result) {

            }

            @Override
            public void onFailure(Throwable e, String errorMsg, int code) {
                ToastUtils.showToast(BaseApplation.instance(), code == 200 ? context.getResources().getString(R.string.getPhoneCodeSuccess) : errorMsg);

            }
        });
    }

    /**
     * 一键登录失败处理
     *
     * @param code
     * @param errorMsg
     */
    private void toFailedActivigy(int code, String errorMsg) {
        String msg = errorMsg;
        if (code == 2003) {
            msg = "网络连接不通";
        } else if (code == 2005) {
            msg = "请求超时";
        } else if (code == 2016) {
            msg = "当前网络环境不支持认证";
        } else if (code == 2010) {
            msg = "未开启读取手机状态权限";
        } else if (code == 6001) {
            msg = "获取loginToken失败";
        } else if (code == 6006) {
            msg = "预取号结果超时，需要重新预取号";
        } else if (code == 6002) {
            msg = "用户取消";
        }
        Toast.makeText(BaseApplation.instance(), msg, Toast.LENGTH_SHORT).show();
    }


    private JVerifyUIConfig getDialogPortraitConfig(Activity activity, int winWidth, int winHeight) {
        int widthDp = px2dip(activity, winWidth);
        JVerifyUIConfig.Builder uiConfigBuilder = new JVerifyUIConfig.Builder().setDialogTheme(widthDp - 60, 300, 0, 0, false);
//        uiConfigBuilder.setLogoHeight(30);
//        uiConfigBuilder.setLogoWidth(30);
//        uiConfigBuilder.setLogoOffsetY(-15);
//        uiConfigBuilder.setLogoOffsetX((widthDp-40)/2-15-20);
//        uiConfigBuilder.setLogoImgPath("logo_login_land");
        uiConfigBuilder.setLogoHidden(true);

        uiConfigBuilder.setNumFieldOffsetY(104).setNumberColor(Color.BLACK);
        uiConfigBuilder.setSloganOffsetY(135);
        uiConfigBuilder.setSloganTextColor(0xFFD0D0D9);
        uiConfigBuilder.setLogBtnOffsetY(161);

        uiConfigBuilder.setPrivacyOffsetY(15);
        uiConfigBuilder.setCheckedImgPath("cb_chosen");
        uiConfigBuilder.setUncheckedImgPath("cb_unchosen");
        uiConfigBuilder.setNumberColor(0xFF222328);
        uiConfigBuilder.setLogBtnImgPath("selector_btn_normal");
        uiConfigBuilder.setPrivacyState(true);
        uiConfigBuilder.setLogBtnText("授权登录");
        uiConfigBuilder.setLogBtnHeight(44);
        uiConfigBuilder.setLogBtnWidth(250);
        uiConfigBuilder.setAppPrivacyColor(0xFFBBBCC5, 0xFF8998FF);
        uiConfigBuilder.setPrivacyText("登录即同意《", "", "", "》并授权车油服获取本机号码");
        uiConfigBuilder.setPrivacyCheckboxHidden(true);
        uiConfigBuilder.setPrivacyTextCenterGravity(true);
//        uiConfigBuilder.setPrivacyOffsetX(52-15);
        uiConfigBuilder.setPrivacyTextSize(10);

        // 图标和标题
        LinearLayout layoutTitle = new LinearLayout(activity);
        RelativeLayout.LayoutParams layoutTitleParam = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutTitleParam.setMargins(0, dp2Pix(activity, 50), 0, 0);
        layoutTitleParam.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        layoutTitleParam.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
        layoutTitleParam.setLayoutDirection(LinearLayout.HORIZONTAL);
        layoutTitle.setLayoutParams(layoutTitleParam);

//        ImageView img = new ImageView(this);
//        img.setImageResource(R.mipmap.logo_login_land);
        TextView tvTitle = new TextView(activity);
        tvTitle.setText("授权于车油服");
        tvTitle.setTextSize(19);
        tvTitle.setTextColor(Color.BLACK);
        tvTitle.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));

//        LinearLayout.LayoutParams imgParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        imgParam.setMargins(0,0,dp2Pix(this,6),0);
        LinearLayout.LayoutParams titleParam = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//        imgParam.setMargins(0,0,dp2Pix(this,4),0);
//        layoutTitle.addView(img,imgParam);
        layoutTitle.addView(tvTitle, titleParam);
        uiConfigBuilder.addCustomView(layoutTitle, false, null);

        // 关闭按钮
        ImageView closeButton = new ImageView(activity);

        RelativeLayout.LayoutParams mLayoutParams1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mLayoutParams1.setMargins(0, dp2Pix(activity, 10.0f), dp2Pix(activity, 10), 0);
        mLayoutParams1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE);
        mLayoutParams1.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        closeButton.setLayoutParams(mLayoutParams1);
        closeButton.setImageResource(R.mipmap.btn_close);
        uiConfigBuilder.addCustomView(closeButton, true, null);

        return uiConfigBuilder.build();
    }


    private int px2dip(Context context, int pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    private int dp2Pix(Context context, float dp) {
        try {
            float density = context.getResources().getDisplayMetrics().density;
            return (int) (dp * density + 0.5F);
        } catch (Exception e) {
            return (int) dp;
        }
    }

    /**
     * 保存登录返回的信息内容
     */
    public void setConfigure(LoginBean data) {
        SPUtil.getInstance().putString(ConfigureFile.JWT, dataIsNull(data.getData().getJwt()));
        SPUtil.getInstance().putString(ConfigureFile.ACCOUNT, dataIsNull(data.getData().getPhone()));
        SPUtil.getInstance().putString(ConfigureFile.ID, dataIsNull(data.getData().getId() + ""));
        SPUtil.getInstance().putBoolean(ConfigureFile.ISLOGIN, true); // 记录已经登录过
        selfPhone.postValue("200");
    }

    /**
     * 处理null数据
     */
    private String dataIsNull(String str) {
        return str == null ? "" : str;
    }
}
